package com.example.fragmentdemo.fragment;

import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;


import com.example.fragmentdemo.MainActivity;
import com.example.fragmentdemo.R;
import com.example.fragmentdemo.adapter.FileAdapter;
import com.example.fragmentdemo.adapter.FragmentTitleAdapter;
import com.example.fragmentdemo.bean.FileBean;
import com.example.fragmentdemo.constant.Constant;
import com.example.fragmentdemo.helper.SQLHelper;
import com.example.fragmentdemo.utils.DateUtil;
import com.google.android.material.tabs.TabLayout;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    private ViewPager viewPager;
    private TabLayout tabLayout;

    private boolean isScanFinish = false;
    private ArrayList<Fragment> fragmentList = new ArrayList<>();

    private List<String> titleList = new ArrayList<>();

    private ProgressBar progressBar;

    private SQLHelper sqlHelper;

    private FragmentTitleAdapter fragmentTitleAdapter;

    //todo
    private ArrayList<FileBean> fileBeanList = new ArrayList<>();
    private ArrayList<FileBean> pdfList;
    private ArrayList<FileBean> pptList;
    private ArrayList<FileBean> docList;
    private ArrayList<FileBean> excelList;
    private ArrayList<FileBean> ettList;
    private ArrayList<FileBean> audioList;
    private ArrayList<FileBean> videoList;
    private ArrayList<FileBean> imgList;

    private ArrayList<FileBean> allList;
    private ArrayList<ArrayList<FileBean>> dataList;
    private boolean isFirstLaunch;
    private SharedPreferences sharedPreferences;

    public HomeFragment() {

    }

    private static class ExampleFragmentViewHolder {
        ExampleFragment exampleFragment;
    }

    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @SuppressLint("MissingInflatedId")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_file, container, false);
        progressBar = view.findViewById(R.id.progressBar);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        sqlHelper = SQLHelper.getInstance(requireContext());
        initView(view);
        showLoading(true);

        //判断是否第一次登录
        sharedPreferences = requireActivity().getPreferences(Context.MODE_PRIVATE);
        isFirstLaunch = sharedPreferences.getBoolean("isFirstLaunch", true);
        new DataAsyncTask().execute();

        initTitle();


    }
    //static 缓存什么时候销毁
    //基础:

    private class DataAsyncTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... voids) {
            fileBeanList = new ArrayList<>();
            String rootPath = Environment.getExternalStorageDirectory().getPath();
            try {
                //如何发现用户编辑了文件,只更新用户编辑的
                //可以添加缓存
                searchForPDFFiles(new File(rootPath));
            } catch (IOException e) {
                e.printStackTrace();
            }
            sqlHelper.insertFileData(fileBeanList);
            return null;
        }


        @Override
        protected void onPostExecute(Void unused) {
            super.onPostExecute(unused);
            // 在主线程中执行初始化数据的操作
            initData();
            fragmentTitleAdapter = new FragmentTitleAdapter(getChildFragmentManager(), fragmentList, titleList);
            viewPager.setAdapter(fragmentTitleAdapter);
            tabLayout.setupWithViewPager(viewPager);
            showLoading(false);
        }

    }


    private class myRunnable implements Runnable {

        @Override
        public void run() {
            getData();

        }
    }

    private void initData() {

        dataList = new ArrayList<>();
        getData();
        ExampleFragmentViewHolder viewHolder;

        if (!dataList.isEmpty()) {
            for (ArrayList<FileBean> list : dataList) {
                viewHolder = new ExampleFragmentViewHolder();
                Log.d(TAG, "initData: " + list);
                viewHolder.exampleFragment = ExampleFragment.newInstance(list);
                fragmentList.add(viewHolder.exampleFragment);
            }

        }


    }

    private void initTitle() {
        titleList.add(Constant.ALL);
        titleList.add(Constant.PDF);
        titleList.add(Constant.PPT);
        titleList.add(Constant.DOC);
        titleList.add(Constant.EXCEL);
        titleList.add(Constant.ETT);
        titleList.add(Constant.AUDIO);
        titleList.add(Constant.VIDEO);
        titleList.add(Constant.IMAGE);
    }


    private void searchForPDFFiles(File directory) throws IOException {
        File[] files = directory.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    Log.d(TAG, "getName: " + file.getName());
                    searchForPDFFiles(file);
                } else {
                    handleFile(file);
                }
            }
        }
    }

    private void handleFile(File file) throws IOException {


        if (file.getName().endsWith(".pdf")) {
            addFileToList(file, "PDF");
        } else if (file.getName().endsWith(".pptx")) {
            addFileToList(file, "PPT");
        } // 添加Word文件
        else if (file.getName().endsWith(".doc") || file.getName().endsWith(".docx")) {
            addFileToList(file, "DOC");
        }// 添加Excel文件
        else if (file.getName().endsWith(".xls") || file.getName().endsWith(".xlsx")) {
            addFileToList(file, "EXCEL");
        }// 添加ETT文件
        else if (file.getName().endsWith(".ett")) {
            addFileToList(file, "ETT");
        }// 添加音频文件
        else if (file.getName().endsWith(".mp3") || file.getName().endsWith(".wav")) {
            addFileToList(file, "AUDIO");
        }// 添加视频文件
        else if (file.getName().endsWith(".mp4") || file.getName().endsWith(".avi")) {
            addFileToList(file, "VIDEO");
            ;
        } // 添加图片文件
        else if (file.getName().endsWith(".jpg") || file.getName().endsWith(".png")) {
            addFileToList(file, "IMAGE");
        }
    }


    private void addFileToList(File file, String fileType) throws IOException {
        FileBean fileBean = new FileBean();
        fileBean.setName(file.getName());
        fileBean.setPath(file.getPath());
        long fileSizeInBytes = file.length();
        long fileSizeInKB = fileSizeInBytes / 1024;
        fileBean.setLength(String.valueOf(fileSizeInKB));
        if ("AUDIO".equals(fileType) || "VIDEO".equals(fileType)) {
            fileBean.setTime(getMediaDuration(file.getPath()));
        }
        fileBean.setCreateTime(DateUtil.format(new Date(file.lastModified())));
        fileBean.setUpdateTime(DateUtil.format(new Date(file.lastModified())));
        fileBean.setFileType(fileType);
        fileBeanList.add(fileBean);
    }


    //计算音视频时长为耗时操作,不应放到主线程中
    public String getMediaDuration(String filePath) throws IOException {
        MediaMetadataRetriever retriever = null;
        try {
            retriever = new MediaMetadataRetriever();
            retriever.setDataSource(filePath);
            String durationStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            if (TextUtils.isEmpty(durationStr)) {
                durationStr = "0";
            }
            long duration = Long.parseLong(durationStr);

            long hours = TimeUnit.MILLISECONDS.toHours(duration);
            long minutes = TimeUnit.MILLISECONDS.toMinutes(duration) % 60;
            long seconds = TimeUnit.MILLISECONDS.toSeconds(duration) % 60;

            return String.format(Locale.getDefault(), Constant.TIME_FORMAT, hours, minutes, seconds);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return Constant.ZERO_FORMAT;
    }


    //从数据库获取数据为耗时操作,不应放到主线程中
    public void getData() {

        allList = new ArrayList<>();
        pdfList = new ArrayList<>();
        pptList = new ArrayList<>();
        docList = new ArrayList<>();
        excelList = new ArrayList<>();
        ettList = new ArrayList<>();
        audioList = new ArrayList<>();
        videoList = new ArrayList<>();
        imgList = new ArrayList<>();

        if (sqlHelper.hasData()) {
            allList = sqlHelper.queryAll();
            pdfList = sqlHelper.queryFileByType(Constant.PDF);
            pptList = sqlHelper.queryFileByType(Constant.PPT);
            docList = sqlHelper.queryFileByType(Constant.DOC);
            excelList = sqlHelper.queryFileByType(Constant.EXCEL);
            ettList = sqlHelper.queryFileByType(Constant.ETT);
            audioList = sqlHelper.queryFileByType(Constant.AUDIO);
            videoList = sqlHelper.queryFileByType(Constant.VIDEO);
            imgList = sqlHelper.queryFileByType(Constant.IMAGE);
        }


        // 将所有数据按顺序添加到 dataList 中
        dataList.add(allList);
        dataList.add(pdfList);
        dataList.add(pptList);
        dataList.add(docList);
        dataList.add(excelList);
        dataList.add(ettList);
        dataList.add(audioList);
        dataList.add(videoList);
        dataList.add(imgList);


    }

    private void getHover(String filePath) throws IOException {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            // 设置数据源为视频文件路径，这里以资源文件为例
            retriever.setDataSource(requireContext(), Uri.parse(filePath));

            // 获取视频文件的第一帧作为封面，可以通过修改时间参数获取不同时间点的帧
            Bitmap bitmap = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            retriever.release();
        }
    }

    private void showLoading(boolean show) {
        if (progressBar != null) {
            progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        }
    }

    private void initView(View view) {
        viewPager = view.findViewById(R.id.home_vp);
        tabLayout = view.findViewById(R.id.tab_layout);

    }
}
